package com.facebook.commands.login 
{
	import com.facebook.Events.FacebookEvent;
	import com.facebook.commands.FacebookCall;
	import com.facebook.commands.query.Query;
	import com.facebook.data.FacebookData;
	import com.facebook.errors.FacebookError;
	import com.facebook.utils.FacebookConnectUtils;

	import flash.external.ExternalInterface;

	/**
	 * @author Ben Smith
	 */
	public class Login extends FacebookCall 
	{
		static public const METHOD : String = "login"
		static public const FUNCTION_CALL : String = "FB.login"
		
		
		private var _permissions:Vector.<String>
		public function Login(permissions:Vector.<String> =null)
		{
			
			
			_permissions=(permissions==null)?(new Vector.<String>()):permissions
		}

		override public function makeCall(format : String = "JSON") : FacebookCall
		{
		
			var _jsCall : String = FUNCTION_CALL + '((' + FacebookConnectUtils.createAnonymousCallFunction()+",{perms:\'"+_permissions.join(',')+"\'})"; 
			FacebookConnectUtils.registerCall(this);
			trace(_jsCall)
			ExternalInterface.call(_jsCall);
			
			return this
		}

		override public function quickTrace() : void
		{
			trace('there is nothing to display')
		}

		override public function handleResult(result : FacebookData) : void 
		{			
				
			if (result.result['session']) {
				dispatchEvent(new FacebookEvent(FacebookEvent.COMPLETE, false, false, true, result));
				dispatchEvent(new FacebookEvent(FacebookEvent.LOGIN_SUCCESS, false, false, true, result));
			}else{
				dispatchEvent(new FacebookEvent(FacebookEvent.LOGIN_FAILURE, false, false, true, result));
			}
		}

		override public function handleError(error : FacebookError) : void 
		{
		
			dispatchEvent(new FacebookEvent(FacebookEvent.COMPLETE, false, false, false, null, error));
		}

		override public function toString() : String
		{
			return Query.METHOD
		}
	}
}
